##
# This class handles the picture-upload
class ImageController < ApplicationController
  helper :paginator
  helper :right
  helper :image
  include PaginatorHelper
  include RightHelper
  include ImageHelper
  layout 'scaffold'
  
  ##
  # redirects to list
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create],
         :redirect_to => { :action => :list }

	# Session must be active
	verify :session => 'user',
				 :redirect_to => { :controller => 'user', :action => :login },
				 :add_flash => { :error => 'you must be logged in to create exams' }

  # verifies that only teacher can access this controller
	before_filter :verify_teacher
  # verifies that only owner of an image can view/destroy it
	before_filter :verify_owner, :only => [:show, :destroy]

  ##
  # lists all images of the logged in user
  def list
    @image_pages, @images = 
			paginate_collection Image.find(:all, :conditions => 
																		 ["user_id = ?", session["user"].id]), 
                                     :order => 'id desc',
													:per_page => 10, :page => params[:page]
  end

  ##
  # shows the corresponding image
  def show
    @image = Image.find(params[:id])
  end

  ##
  # creates an upload form
  def new
    @image = Image.new
  end

  ##
  # stores the uploaded image in the DB and in the FS
  def create
    begin
	    @image = Image.new(params[:image])
	    @image.user = session['user']
	    if @image.save
	      flash[:notice] = 'Image was successfully created.'
	      redirect_to :action => 'list'
	    else
	      render :action => 'new'
	    end
    rescue ImageHelper::NoImage => error
      flash[:error] = "Sorry, your file is no image!"
      render :action => 'new'
    rescue ImageHelper::FileExists => error
      flash[:error] = "Sorry the file already exists..."
      render :action => 'new'
    end
  end

  ##
  # destroys an image from the DB and the Filesystem
  def destroy
    img = Image.find(params[:id])
    File.delete("#{RAILS_ROOT}/media/#{img.file}") if \
      File.exist?("#{RAILS_ROOT}/media/#{img.file}")
    img.destroy
    redirect_to :action => 'list'
  end
  
  private
  
  ##
  # Verfies that the image in the GET-variable is owned by the currently logged
  # in user
  def verify_owner
    image = Image.find(params[:id])
    if image.nil?
      flash[:error] = 'Error Exam doesn\'t exists'
      redirect_to :action => :list
    end
    if image.user != session['user']
      flash[:error] = 'Sorry, but you are not the owner of this image'
      redirect_to :action => :list
    end
  end
end
